<template>
  <div class="home">
    <!-- 用户信息卡片 -->
    <div class="userInfo">
      <el-avatar :size="50" :src="storeUser.userInfo.avatar" />
      <div>
        <p class="name">你好 {{ storeUser.userInfo.name || storeUser.userInfo.username }}</p>
        <p class="role">角色: {{ storeUser.userRoles.join(', ') }}</p>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon users">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ systemStore.systemStats.totalUsers }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon orders">
            <el-icon><ShoppingCart /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ systemStore.systemStats.totalOrders }}</div>
            <div class="stat-label">总订单数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon revenue">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">¥{{ systemStore.systemStats.totalRevenue.toLocaleString() }}</div>
            <div class="stat-label">总收入</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon products">
            <el-icon><Box /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ systemStore.systemStats.totalProducts }}</div>
            <div class="stat-label">商品数量</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-case">
      <div class="charts-chunk">
        <div ref="chartsDiscount" style="width: 100%; height: 400px"></div>
      </div>
      <div class="charts-chunk">
        <div ref="chartsCake" style="width: 100%; height: 400px"></div>
      </div>
      <div class="charts-chunk">
        <div ref="chartsColumn" style="width: 100%; height: 400px"></div>
      </div>
    </div>

    <!-- 通知区域 -->
    <div class="notifications-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>系统通知</span>
            <el-badge :value="systemStore.unreadCount" class="notification-badge">
              <el-button type="primary" size="small" @click="refreshNotifications">
                刷新通知
              </el-button>
            </el-badge>
          </div>
        </template>
        <div class="notifications-list">
          <div 
            v-for="notification in systemStore.notifications.slice(0, 5)" 
            :key="notification.id"
            class="notification-item"
            :class="{ 'unread': !notification.isRead }"
            @click="markAsRead(notification.id)"
          >
            <div class="notification-icon">
              <el-icon v-if="notification.type === 'warning'"><Warning /></el-icon>
              <el-icon v-else-if="notification.type === 'error'"><CircleClose /></el-icon>
              <el-icon v-else><InfoFilled /></el-icon>
            </div>
            <div class="notification-content">
              <div class="notification-title">{{ notification.title }}</div>
              <div class="notification-desc">{{ notification.content }}</div>
              <div class="notification-time">{{ notification.time }}</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import { useUser } from "@/store/user.js";
import { useSystem } from "@/store/system.js";
import { User, ShoppingCart, Money, Box, Warning, CircleClose, InfoFilled } from "@element-plus/icons-vue";

const storeUser = useUser();
const systemStore = useSystem();

// 定义变量内容
const chartsDiscount = ref();
const chartsCake = ref();
const chartsColumn = ref();
const chartsObj = {
  chartsDiscount: "",
  chartsCake: "",
  chartsColumn: "",
  myCharts: [],
};

// 初始化折线图 - 用户增长趋势
function initDeicount() {
  chartsObj.chartsDiscount = echarts.init(chartsDiscount.value);
  const option = {
    title: {
      text: "用户增长趋势",
      top: "2%",
      left: "2%",
    },
    legend: {
      top: "8%",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: systemStore.chartData.userGrowth.map(item => item.month),
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "用户数量",
        data: systemStore.chartData.userGrowth.map(item => item.users),
        type: "line",
        smooth: true,
        itemStyle: {
          color: "#409EFF"
        }
      },
    ],
  };
  chartsObj.chartsDiscount.setOption(option);
  chartsObj.myCharts.push(chartsObj.chartsDiscount);
}

// 初始化饼图 - 销售数据
function initCake() {
  chartsObj.chartsCake = echarts.init(chartsCake.value);
  const option = {
    title: {
      text: "销售数据分布",
      top: "2%",
      left: "2%",
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    legend: {
      top: "8%",
      left: "center",
    },
    series: [
      {
        name: "销售数据",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: systemStore.chartData.salesData.map(item => ({
          value: item.value,
          name: item.name
        })),
      },
    ],
  };
  chartsObj.chartsCake.setOption(option);
  chartsObj.myCharts.push(chartsObj.chartsCake);
}

// 初始化柱状图 - 订单状态
function initColumn() {
  chartsObj.chartsColumn = echarts.init(chartsColumn.value);
  var option = {
    title: {
      text: "订单状态分布",
      top: "2%",
      left: "2%",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {},
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
    },
    yAxis: {
      type: "category",
      data: systemStore.chartData.orderStatus.map(item => item.status),
    },
    series: [
      {
        name: "订单数量",
        type: "bar",
        data: systemStore.chartData.orderStatus.map(item => item.count),
        itemStyle: {
          color: "#67C23A"
        }
      },
    ],
  };
  chartsObj.chartsColumn.setOption(option);
  chartsObj.myCharts.push(chartsObj.chartsColumn);
}

// 批量设置 echarts resize
function initEChartsResize() {
  var myEvent = new Event("resize");
  window.addEventListener("resize", () => {
    nextTick(() => {
      for (let i = 0; i < chartsObj.myCharts.length; i++) {
        setTimeout(() => {
          chartsObj.myCharts[i].resize();
        }, 1000);
      }
    });
  });
  window.dispatchEvent(myEvent);
}

// 刷新通知
async function refreshNotifications() {
  try {
    await systemStore.fetchNotifications();
    ElMessage.success("通知已刷新");
  } catch (error) {
    ElMessage.error("刷新通知失败");
  }
}

// 标记通知为已读
async function markAsRead(id) {
  try {
    await systemStore.markNotificationAsRead(id);
    ElMessage.success("已标记为已读");
  } catch (error) {
    ElMessage.error("标记失败");
  }
}

// 初始化数据
async function initData() {
  try {
    await systemStore.initSystemData();
    // 数据加载完成后初始化图表
    await nextTick();
    initDeicount();
    initCake();
    initColumn();
    initEChartsResize();
  } catch (error) {
    console.error("初始化数据失败:", error);
    ElMessage.error("数据加载失败");
  }
}

onMounted(() => {
  initData();
});

onActivated(() => {
  initEChartsResize();
});
</script>

<style lang="scss" scoped>
.userInfo {
  padding: 20px;
  width: 100%;
  display: flex;
  align-items: center;
  gap: 0 20px;
  border: 1px solid #eee;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  
  .name {
    font-size: 20px;
    font-weight: 600;
    margin: 0;
  }
  
  .role {
    font-size: 14px;
    color: #666;
    margin: 5px 0 0 0;
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  
  .stat-content {
    display: flex;
    align-items: center;
    gap: 15px;
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;
      
      &.users {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.orders {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.revenue {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.products {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 5px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.charts-case {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: repeat(2, 1fr);
  gap: 10px;
  grid-template-areas:
    "a b"
    "c c";
  margin-bottom: 20px;
}

.charts-chunk {
  border: 1px solid #eee;
  border-radius: 8px;
  background: white;
}

.charts-chunk:nth-child(1) {
  grid-area: a;
}

.charts-chunk:nth-child(2) {
  grid-area: b;
}

.charts-chunk:last-child {
  grid-area: c;
}

.notifications-section {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .notification-badge {
      margin-left: 10px;
    }
  }
  
  .notifications-list {
    max-height: 400px;
    overflow-y: auto;
  }
  
  .notification-item {
    display: flex;
    align-items: flex-start;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background-color 0.3s;
    
    &:hover {
      background-color: #f5f5f5;
    }
    
    &.unread {
      background-color: #f0f9ff;
      border-left: 3px solid #409EFF;
    }
    
    .notification-icon {
      margin-right: 15px;
      margin-top: 5px;
      
      .el-icon {
        font-size: 20px;
        
        &.warning {
          color: #E6A23C;
        }
        
        &.error {
          color: #F56C6C;
        }
        
        &.info {
          color: #409EFF;
        }
      }
    }
    
    .notification-content {
      flex: 1;
      
      .notification-title {
        font-weight: bold;
        margin-bottom: 5px;
        color: #333;
      }
      
      .notification-desc {
        color: #666;
        margin-bottom: 5px;
        line-height: 1.4;
      }
      
      .notification-time {
        font-size: 12px;
        color: #999;
      }
    }
  }
}
</style>
